import React from 'react';
import { Modal, Button } from 'antd';
import baseService from 'share/base.service';
import banner from 'images/login/update-notice.jpg';

class UpdateNotice extends React.Component {

  constructor() {
    super();
    console.log('UpdateNotice');
    this.state = {
      eid: '',
      /** 正在检查中 */
      checking: false,
      /** 正在确认中 */
      confirming: false,
      /** 通知是否已经确认阅读过了： -1未检查，0未确认阅读，1已确认阅读，2接口出错 */
      noticeConfirmStatus: -1,
      /** 当通知状态检查出错时，{ response: { message: 'xxx' } } */
      noticeCheckError: null,
    };
  }

  componentDidUpdate() {
    if (this.state.noticeConfirmStatus === -1 && !this.state.checking) {
      this.checkNotice();
    }
  }

  checkNotice = async () => {
    let error = null;
    let res = null;
    try {
      this.setState({ checking: true })
      res = await baseService.checkNotice();
      // res = { data: { false: null } }
      // throw { response: { message: 'MOCK一个错误异常出来' } }
      if (res.status !== 200) {
        throw res;
      }
    } catch (e) {
      error = e;
      this.setState({
        noticeConfirmStatus: 2,
        checking: false,
        noticeCheckError: e
      });
    }
    if (!error) {
      this.setState({
        // true:'$1' 是已经点过确定不需要提示(1)，false:null是未点过确定需要提示(0)
        noticeConfirmStatus: res.data.true ? 1 : 0,
        eid: res.data.true,
        checking: false,
        noticeCheckError: null,
      });
    }
  }

  confirm = async () => {
    try {
      let res = null;
      this.setState({confirming: true});
      res = await baseService.confirmNotice();
      if (res.status !== 200) {
        throw res;
      }

      this.setState({confirming: false, noticeConfirmStatus: 1});
    } catch (e) {
      this.setState({confirming: false, noticeConfirmStatus: 1});
    }
  }

  render() {
    return (
      <Modal
        closable={false}
        keyboard={false}
        maskClosable={false}
        visible={this.state.noticeConfirmStatus === 0}
        footer={<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
          <Button type="primary" onClick={this.confirm} loading={this.state.confirming}>我已知晓</Button>
        </div>}
      >
        <div className="auth-modal-box">
          <div className="box-content">
            <img src={banner} alt="费用管控更新" style={{ width: 'auto', height: 500, maxHeight: '70vh' }} />
          </div>
        </div>
      </Modal>
    );
  }
}

export default UpdateNotice;
